﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mobile_VTBL.UI
{
    public class UserContext
    {
        public enum CustomerGroup { Per = 0, Org = 1 };
        public static string ErrMsg = string.Empty;
        public static string NavigateUrl = string.Empty;
        public static string PathPage = string.Empty;
        //protected FileConfig CFG = FileConfig.Current;
        private static UserContext _current;

        static UserContext()
        {
            _current = new UserContext();
        }

        public static UserContext Current
        {
            get
            {
                return _current;
            }
        }
        #region delete
        /*public void excuteScript(string key, string function)
        {
            Page page = HttpContext.Current.Handler as Page;
            ScriptManager.RegisterClientScriptBlock(page, page.GetType(), key, function, true);
        }
        public string GetInfo(string UserName, string FieldName)
        {
            System.Web.Profile.ProfileBase objProfile;
            string returnVal = "";
            objProfile = AspNetProfile.ProfileBase.Create(UserName);
            if (objProfile != null)
            {
                returnVal = objProfile[FieldName].ToString();
            }
            return returnVal != "" ? returnVal : "";

        }

        #region IsAdmin
        public bool IsLogin
        {
            get
            {
                return HttpContext.Current.User.Identity.IsAuthenticated;
            }
        }
        #endregion

        #region GetUserName
        /// <summary>
        /// Get UserName
        /// </summary>
        /// <param name="UserId">UserId</param>
        /// <returns></returns>
        public string GetUserName(Guid UserId)
        {
            MembershipUser aMembershipUser = Membership.GetUser(UserId);
            return aMembershipUser.UserName;
        }
        public string GetUserName(string Email)
        {
            string v = string.Empty;
            try
            {
                return Membership.GetUserNameByEmail(Email).Trim();
            }
            catch (Exception)
            {
                return (string.Empty);
            }
        }
        public string GetEmail(string UserName)
        {
            string returnVal = UserName;

            ProfileBase aProfileBase = ProfileBase.Create(UserName);
            if (aProfileBase != null && aProfileBase.GetPropertyValue("e_email") != null && Convert.ToString(aProfileBase.GetPropertyValue("e_email")).Length > 0)
                returnVal = Convert.ToString(aProfileBase.GetPropertyValue("e_email"));

            return returnVal;
        }
        public string GetInfoEmp(string UserName)
        {
            string returnVal = "";
            if (UserName != null && UserName != "")
            {
                if (UserName.Trim() != "")
                {
                    returnVal += "<div class='infoEmp'>";
                    returnVal += GetFullName(UserName);
                    returnVal += "<span>" + UserName + "</span>";
                    returnVal += "   <div class='sub_info'><img alt='' src='/Web/Imgs/loading.gif'/></div>";
                    returnVal += "</div>";
                }
            }
            return returnVal;
        }
        public string GetFullName(string UserName)
        {
            string returnVal = UserName;

            ProfileBase aProfileBase = ProfileBase.Create(UserName);
            if (aProfileBase != null && aProfileBase.GetPropertyValue("e_name") != null && Convert.ToString(aProfileBase.GetPropertyValue("e_name")).Length > 0)
                returnVal = Convert.ToString(aProfileBase.GetPropertyValue("e_name"));

            return returnVal;
        }
        public int GetDeptID(string UserName)
        {
            int returnVal = 0;

            ProfileBase aProfileBase = ProfileBase.Create(UserName);
            if (aProfileBase != null && aProfileBase.GetPropertyValue("Deptid") != null && Convert.ToString(aProfileBase.GetPropertyValue("Deptid")).Length > 0)
                returnVal = Convert.ToInt32(aProfileBase.GetPropertyValue("Deptid"));

            return returnVal;
        }
        #endregion

        #region GetCulture
        /// <summary>
        /// Get Language
        /// 
        /// sdfsdfsf
        /// </summary>
        /// <returns>String</returns>
        public string GetCulture()
        {
            string returnVal = "";
            returnVal = CultureInfo.CurrentCulture.Name;
            return returnVal;
        }
        #endregion

        #region GetLanguage
        public string GetLanguage()
        {
            string returnVal = "";
            switch (GetCulture())
            {
                case "vi-VN":
                    returnVal = "VN";
                    break;
                case "en-US":
                    returnVal = "EN";
                    break;
            }
            return returnVal;
        }
        #endregion

        #region GetUserId
        /// <summary>
        /// Get UserId
        /// </summary>
        /// <param name="UserName">UserName</param>
        /// <returns></returns>
        public Guid GetUserId(string UserName)
        {
            MembershipUser aMembershipUser = Membership.GetUser(UserName);
            return (Guid)aMembershipUser.ProviderUserKey;
        }
        #endregion

        #region IsNumeric
        /// <summary>
        /// Ex Input is a numeric
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public bool IsNumeric(string Text)
        {
            if (Text == "" || Text == null)
            {
                return false;
            }
            Text = Text.Trim();
            bool bResult = Regex.IsMatch(Text, @"^\d+$");
            return bResult;
        }
        #endregion

        #region IsDate
        /// <summary>
        /// IsDate
        /// </summary>
        /// <param name="Text">String</param>
        /// <returns>True or False?</returns>
        public bool IsDate(string Text)
        {
            bool result = true;
            DateTime date;

            try
            {
                date = Convert.ToDateTime(Text);
            }
            catch
            {
                result = false;
            }

            return result;
        }
        #endregion

        #region IsMail
        /// <summary>
        /// Email is Valid?
        /// </summary>
        /// <param name="StrInput"></param>
        /// <returns></returns>
        public bool CheckMail(string StrInput)
        {
            bool returnVal = false;

            string StrPatern = "([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})";
            Match m = Regex.Match(StrInput, StrPatern);
            if (m.Success)
                returnVal = true;

            return returnVal;
        }
        #endregion

        #region TryParse
        /// <summary>
        /// Converts the string representation of a number to its 32-bit signed integer equivalent. Returns 0 if the conversion fails.
        /// </summary>
        public int TryParse(string s)
        {
            return TryParse(s, 0);
        }

        /// <summary>
        /// Converts the string representation of a number to its 32-bit signed integer equivalent. Returns defaultValue if the conversion fails.
        /// </summary>
        public int TryParse(string s, int defaultValue)
        {
            try
            {
                return int.Parse(s);
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// Converts the string representation of a number to its 32-bit signed integer equivalent. Returns defaultValue if the conversion fails.
        /// </summary>
        public long TryParse(string s, long defaultValue)
        {
            try
            {
                return int.Parse(s);
            }
            catch
            {
                return defaultValue;
            }
        }

        public DateTime TryParseToDateTime(object d)
        {
            try
            {
                return Convert.ToDateTime(d);
            }
            catch
            {
                return new DateTime(0);
            }
        }
        public bool IsInt32(string input)
        {
            try
            {
                Convert.ToInt32(input);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool IsFloat(string input)
        {
            try
            {
                Convert.ToSingle(input);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region Cast
        public string Cast(object o)
        {
            return Cast(o, string.Empty);
        }

        public string Cast(object o, string defaultValue)
        {
            return (o is string ? (string)o : defaultValue);
        }
        #endregion

        #region Remove Html Tags
        /// <summary>
        /// Remove Html Tag
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public string StripHtmlTags(string html)
        {
            Regex regex = new Regex("<[^>]*>", RegexOptions.Multiline);

            return regex.Replace(html, string.Empty);
        }
        #endregion

        #region RandomString
        /// <summary>
        /// Random String
        /// </summary>
        /// <param name="length">Length</param>
        /// <returns></returns>
        public string RandomString(int length)
        {
            const string symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

            Random rnd = new Random();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                sb.Append(symbols[rnd.Next(0, symbols.Length)]);
            }

            return sb.ToString();
        }
        /// <summary>
        /// Random String
        /// </summary>
        /// <param name="length">Length</param>
        /// <returns></returns>
        public string RandomNumber(int length)
        {
            const string symbols = "0123456789";

            Random rnd = new Random();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                sb.Append(symbols[rnd.Next(0, symbols.Length)]);
            }

            return sb.ToString();
        }
        #endregion

        #region send mail
        public bool SendMail(string NameFrom, string EmailFrom, string NameTo, string EmailTo, string NameCc, string EmailCc, string NameBcc, string EmailBcc, string Subject, string Content, bool IsHTML)
        {
            MailMessage msg = new MailMessage();

            //msg.SMTPServer.Host = ConfigurationManager.AppSettings["SMTPServer"].ToString();
            //msg.SMTPServer.Username = ConfigurationManager.AppSettings["SMTPServerUsername"].ToString();
            //msg.SMTPServer.Password = ConfigurationManager.AppSettings["SMTPServerPassword"].ToString();
            //msg.SMTPServer.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPServerPort"].ToString());            
            //msg.SMTPServer.DisableExceptions = true;

            /// From
            msg.From.Name = NameFrom;
            msg.From.EMail = EmailFrom;

            /// To
            msg.To.Add(NameTo, EmailTo);

            /// CC
            msg.Cc.Add(NameCc, EmailCc);

            /// BCC
            msg.Bcc.Add(NameBcc, EmailBcc);

            /// Subject
            msg.Subject = Subject;

            /// Content
            if (IsHTML)
            {
                msg.Charset = "UTF-8";
                msg.HTMLMessage.Body = Content;
                /// Config
                msg.HTMLMessage.BodyEncoding = Encoding.UTF8;

            }
            else
            {
                msg.Charset = "UTF-8";
                msg.Body = Content;
                /// Config
                msg.BodyEncoding = Encoding.UTF8;

            }

            return msg.Send();
        }

        public bool SendMail(string NameFrom, string EmailFrom, string NameTo, string EmailTo, string Subject, string Content, bool IsHTML)
        {
            MailMessage msg = new MailMessage();

            /// SMTP
            msg.SMTPServer.Host = ConfigurationManager.AppSettings["SMTPServer"].ToString();
            msg.SMTPServer.Username = ConfigurationManager.AppSettings["SMTPServerUsername"].ToString();
            msg.SMTPServer.Password = ConfigurationManager.AppSettings["SMTPServerPassword"].ToString();
            msg.SMTPServer.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPServerPort"].ToString());
            msg.SMTPServer.DisableExceptions = true;
            msg.SMTPServer.UseDefaultCredentials = true;

            /// From
            msg.From.Name = NameFrom;
            msg.From.EMail = EmailFrom;

            /// To
            msg.To.Add(NameTo, EmailTo);

            /// Subject
            msg.Subject = Subject;

            /// Content
            if (IsHTML)
            {
                msg.Charset = "UTF-8";
                msg.HTMLMessage.Body = Content;
                /// Config
                msg.HTMLMessage.BodyEncoding = Encoding.UTF8;

            }
            else
            {
                msg.Charset = "UTF-8";
                msg.Body = Content;
                /// Config
                msg.BodyEncoding = Encoding.UTF8;

            }
            return msg.Send();

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="EmailFrom"></param>
        /// <param name="NameFrom"></param>
        /// <param name="NameTo"></param>
        /// <param name="EmailTo"></param>
        /// <param name="Subject"></param>
        /// <param name="Content"></param>
        /// <param name="IsHTML"></param>
        /// <returns></returns>
        public bool UpdateSendMail(string EmailFrom, string NameFrom, string NameTo, string EmailTo, string Subject, string Content, bool IsHTML)
        {
            bool result = true;
            try
            {
                PromotionEmailQueue aPromotionEmailQueue = new PromotionEmailQueue();
                aPromotionEmailQueue.EmailID = Guid.NewGuid();
                aPromotionEmailQueue.emailTo = NameTo + "<" + EmailTo + ">";
                aPromotionEmailQueue.emailSubject = Subject;
                aPromotionEmailQueue.emailFrom = NameFrom + " <" + EmailFrom + ">";
                aPromotionEmailQueue.IsHTML = IsHTML;
                aPromotionEmailQueue.NumberOfTries = 0;
                aPromotionEmailQueue.LastSendDate = DateTime.Now;
                aPromotionEmailQueue.emailBody = Content;
                aPromotionEmailQueue.Append();
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region RequestQueryString
        /// <summary>
        /// Get Value Of QueryString
        /// </summary>
        /// <param name="QueryName"></param>
        /// <param name="DefaultValue"></param>
        /// <returns>long</returns>
        public int RequestQueryString(string QueryName, int DefaultValue)
        {
            int returnVal = TryParse(DefaultValue.ToString(), 0);

            ///Request QueryString
            if (HttpContext.Current.Request.QueryString[QueryName] != null && IsNumeric(HttpContext.Current.Request.QueryString[QueryName].ToString()))
            {
                returnVal = System.Convert.ToInt32(HttpContext.Current.Request.QueryString[QueryName].ToString().Replace("#", ""));
            }
            ///Return
            return returnVal > int.MaxValue ? 0 : returnVal;
        }
        #endregion

        #region RequestQueryString
        /// <summary>
        /// Get Value Of QueryString
        /// </summary>
        /// <param name="QueryName">string QueryName</param>
        /// <param name="DefaultValue">string DefaultValue</param>
        /// <returns>string</returns>
        public string RequestQueryString(string QueryName, string DefaultValue)
        {
            string returnVal = ((DefaultValue != null) ? DefaultValue : "");

            ///Request QueryString
            if (HttpContext.Current.Request.QueryString[QueryName] != null)
            {
                returnVal = HttpContext.Current.Request.QueryString[QueryName].ToString().Replace("'", "''").Replace("\"", "").Replace("#", "");
            }

            ///Return
            return returnVal.Trim();
        }
        #endregion

        #region UpdateQueryString
        public string UpdateQueryString(string QueryStringKey, string QueryStringValue, string Url)
        {
            string NewUrl = Url;
            if (Url == "")
            {
                NewUrl = HttpContext.Current.Request.Url.PathAndQuery;
            }
            string PageUrl = NewUrl;
            if (NewUrl.IndexOf("?", 0) >= 0)
                PageUrl = NewUrl.Substring(0, NewUrl.IndexOf("?", 0));

            string NewKey = QueryStringKey + "=" + QueryStringValue;
            string NewQueryString = "";

            string OldQueryString = "";
            if (NewUrl.IndexOf("?", 0) >= 0)
                OldQueryString = NewUrl.Substring(NewUrl.IndexOf("?", 0) + 1);

            if (OldQueryString != "" && QueryStringKey != "")
            {
                string[] ArrayQuery = OldQueryString.Split('&');
                for (int i = 0; i < ArrayQuery.Length; i++)
                {
                    if (string.Compare(QueryStringKey, ArrayQuery[i].Substring(0, ArrayQuery[i].LastIndexOf("=")), true) == 0)
                    {
                        //NewQueryString += NewKey;
                    }
                    else
                    {
                        if (NewQueryString != "")
                            NewQueryString += "&";

                        NewQueryString += ArrayQuery[i];
                    }
                }


                if (QueryStringValue != "")
                {
                    if (NewQueryString != "")
                        NewQueryString += "&";

                    NewQueryString += NewKey;
                }


                if (NewQueryString != "")
                    NewUrl = PageUrl + "?" + NewQueryString;
                else
                    NewUrl = PageUrl;

            }
            else
            {
                if (QueryStringKey != "" && QueryStringValue != "")
                {
                    NewUrl = PageUrl + "?" + NewKey;
                }
            }
            return NewUrl;
        }
        #endregion

        #region ShowEnVn
        public string ShowEnVn(string Language, string EnString, string VnString)
        {
            if (Language == "enUS")
                return EnString;
            else
                return VnString;
        }
        #endregion

        #region GetImage
        /// <summary>
        /// Get thumbnail of Image. (ImagePath get from WEb.config)
        /// </summary>
        /// <param name="StrFile"></param>
        /// <returns></returns>
        public string GetImage(string StrFile)
        {
            string StrImagePath = CFG.ImagePath();
            string returnVal = "";

            if (StrFile != "")
            {
                string StrFullPath = StrImagePath + "/" + StrFile;

                StrFullPath = StrFullPath.Replace("//", "/");

                if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                {
                    returnVal = StrImagePath + "/noimage.gif";
                }
                else
                {
                    returnVal = StrFullPath;
                }
            }
            else
                returnVal = StrImagePath + "/noimage.gif";

            returnVal = returnVal.Replace("//", "/");
            return returnVal;
        }
        #endregion

        #region GetImageThumb
        /// <summary>
        /// Get thumbnail of Image. (ImagePath get from WEb.config)
        /// </summary>
        /// <param name="StrFile"></param>
        /// <returns></returns>
        public string GetImageThumb(string StrFile, int Width, int Height)
        {
            string StrImagePath = CFG.ImagePath();
            string returnVal = "";

            if (StrFile != "")
            {
                string StrFullPath = StrImagePath + "/" + Width.ToString() + "x" + Height.ToString() + "_" + StrFile;

                StrFullPath = StrFullPath.Replace("\\", "/");
                StrFullPath = StrFullPath.Replace("//", "/");

                try
                {
                    if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                    {
                        string OldImage = StrImagePath + "/" + StrFile;
                        OldImage = OldImage.Replace("\\", "/");
                        OldImage = OldImage.Replace("//", "/");

                        if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(OldImage)))
                            returnVal = StrImagePath + "/noimage.gif";
                        else
                            returnVal = this.GetThumb(StrFile, Width, Height, "", false, "");

                    }
                    else
                    {
                        returnVal = StrFullPath;
                    }
                }
                catch
                {
                    returnVal = StrImagePath + "/noimage.gif";
                }
            }
            else
                returnVal = StrImagePath + "/noimage.gif";

            returnVal = returnVal.Replace("//", "/");
            return returnVal;
        }
        #endregion

        #region GetImage
        /// <summary>
        /// Get  Image. (ImagePath get from WEb.config)
        /// </summary>
        /// <param name="StrFile"></param>
        /// <returns></returns>
        public string GetImage(string StrFile, bool BolConvertToDefaultImage, string DefaultImage)
        {
            string StrImagePath = CFG.ImagePath();
            string StrFullPath = StrImagePath + "/" + StrFile;
            StrFullPath = StrFullPath.Replace("//", "/");

            string returnVal = "";
            if (BolConvertToDefaultImage)
                returnVal = StrImagePath + "/" + DefaultImage;

            if (StrFile != "")
            {
                if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                {
                    returnVal = StrImagePath + "/noimage.gif";
                }
                else
                {
                    returnVal = StrFullPath;
                }
            }
            returnVal = returnVal.Replace("//", "/");
            return returnVal;
        }
        #endregion

        #region Paper
        public string PageCtrl(String Url, Int32 CurPage, Int32 TotalRecord, Int32 PageSize, Int32 ShowPages)
        {
            Int32 PStart = (CurPage - CurPage % ShowPages) + 1;
            if (CurPage < PStart)
                PStart -= 1;

            Int32 PEnd = PStart + ShowPages;
            //Int32 PTotal = (TotalRecord - TotalRecord % PageSize) / PageSize + ((TotalRecord % PageSize > 0) ? (1) : (0));

            Int32 PTotal = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(TotalRecord) / Convert.ToDouble(PageSize)));
            if (PTotal == 0)
                PTotal = 1;

            if (PEnd > PTotal)
            {
                PEnd = PTotal + 1;
                PStart = Math.Max(1, PEnd - ShowPages);
            }

            string SepStr = "";

            CurPage = Math.Min(CurPage, PTotal);
            string VarName = "Page";
            int VarValueIndex;
            Match match = Regex.Match(Url, @"([&\?]" + VarName + @"=)(\d{0,})", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                Url = Url.Remove(match.Groups[2].Index, match.Groups[2].Length);
                VarValueIndex = match.Groups[2].Index;
            }
            else
            {
                if (Regex.IsMatch(Url, @"\?\w+="))
                    Url += "&" + VarName + "=";
                else
                    Url += "?" + VarName + "=";
                VarValueIndex = Url.Length;
            }

            String strPage = String.Empty;

            if (CurPage > 1)
                strPage += "<span class=OnPrev><a class=OnPrev href=\"" +
                    Url.Insert(VarValueIndex, (CurPage - 1).ToString()) +
                    "\"><img src='/Web/Imgs/Icon/btnPrevious.gif' border=0 class='Img1' /></a></span>";
            else
                strPage += "<span class=OffPrev><img src='/Web/Imgs/Icon/btnPrevious.gif' border=0 class='Img1' /></span>";

            for (int i = PStart; i < PEnd; i++)
            {
                if (i > PStart)
                    strPage += SepStr;

                if (i == CurPage)
                {
                    strPage += String.Format("<span class=OffPage>{0}</span>", i.ToString() + "/" + PTotal.ToString());
                }
                else
                {
                    strPage += "<span class=OnPage><a class=OnPage href=\"" +
                        Url.Insert(VarValueIndex, i.ToString()) +
                        "\">" + i + "</a></span>";
                }
            }

            if (CurPage < PTotal)
                strPage +=
                    "<span class=OnNext><a class=OnNext href=\"" +
                    Url.Insert(VarValueIndex, (CurPage + 1).ToString()) +
                    "\"><img src='/Web/Imgs/Icon/btnNext.gif' border=0 class='Img2' /></a></span>";
            else
                strPage += "<span class=OffNext><img src='/Web/Imgs/Icon/btnNext.gif' border=0 class='Img2' /></span>";

            return strPage;
        }
        #endregion

        #region Get Intro
        public string Concat(string text, int length)
        {
            text = RemoveTag(text);
            int Pos = 0;
            string returnVal = "";
            returnVal = text.Trim();
            if (returnVal.Length > length)
            {
                returnVal = returnVal.Substring(0, length);
            }

            Pos = returnVal.LastIndexOf(" ");
            if (Pos == length - 1)
            {
                returnVal = returnVal.Trim();
            }
            else
            {
                if (text.Trim().Length > length && text.Trim().Substring(length, 1) == " ")
                    returnVal = returnVal.Substring(0, Pos);
            }

            if (returnVal.Trim().Length < text.Trim().Length)
                returnVal = returnVal + " ...";


            return RemoveTag(returnVal);

        }
        public string RemoveTag(string strContent)
        {
            MatchCollection mc = new Regex("<[^>]*>", RegexOptions.IgnoreCase).Matches(strContent);
            for (int i = 0; i < mc.Count && mc[i].Success; i++)
            {
                strContent = strContent.Replace(mc[i].Value, "");
            }
            return strContent;
        }

        #endregion

        #region GetFileName
        /// <summary>
        /// Get current FileName
        /// </summary>
        /// <returns></returns>
        public string GetFileName()
        {
            string Path = HttpContext.Current.Request.Path.ToString();
            int IntPos = Path.LastIndexOf("/") + 1;
            return Path.Substring(IntPos, Path.Length - IntPos);
        }
        #endregion

        #region split
        public DataTable SplitString(string Value)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Value");

            string[] arrValue = Value.Split(',');
            foreach (string item in arrValue)
            {
                dt.Rows.Add(item);
            }
            return dt;
        }
        public DataTable SplitString(string Value, string Text)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Value");
            dt.Columns.Add("Text");

            string[] arrValue = Value.Split(',');
            string[] arrText = Text.Split(',');
            int i = 0;
            foreach (string item in arrValue)
            {
                dt.Rows.Add(item, arrText[i]);
                i++;
            }
            return dt;
        }
        #endregion

        #region Resize
        /// <summary>
        /// Resize Image
        /// </summary>
        /// <param name="PhysicalImagePath"></param>
        /// <param name="PhysicalOutPath"></param>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <returns></returns>
        public string Resize(string PhysicalImagePath, string PhysicalOutPath, int Width, int Height)
        {
            System.Drawing.Image OImage = System.Drawing.Image.FromFile(PhysicalImagePath);

            System.Drawing.Image aThumbNail = OImage;//new Bitmap(Width, Height, OImage.PixelFormat);

            IntPtr intP = new IntPtr();
            string returnVal = string.Empty;
            try
            {
                if (Width > 0 && Height > 0)
                {
                    aThumbNail = OImage.GetThumbnailImage(Width, Height, null, intP);
                }
                else
                {
                    aThumbNail = OImage;
                }
            }
            catch { }
            finally
            {
                OImage.Dispose();
                aThumbNail.Save(PhysicalOutPath);
            }
            aThumbNail.Dispose();
            OImage.Dispose();
            return PhysicalOutPath;
        }
        #endregion

        public string GetThumb(string StrFile, int Width, int Height, string FolderThumbnail, bool ConvertToDefaultFile, string DefaultFile)
        {
            string StrImagePath = CFG.ImagePath();
            string StrImageThumb = "";
            string returnVal = "";
            bool BResize = false;
            bool BCrop = false;
            int RWidth = 0;
            int RHeight = 0;
            int w = Width;
            int h = Height;
            float Ratio = 0;

            // Duong dan

            string StrFullPath = StrImagePath + "/" + StrFile;
            StrFullPath = StrFullPath.Replace("\\", "/");
            StrFullPath = StrFullPath.Replace("//", "/");

            if (StrFile != "")
            {

                if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                {
                    return "";

                }

                string Ext = StrFullPath.Substring(StrFullPath.LastIndexOf(".") + 1);
                System.Drawing.Image OImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(StrFullPath));
                int OWidth = OImage.Width;
                int OHeight = OImage.Height;
                if (Width > OWidth)
                    Width = OWidth;
                if (Height > OHeight)
                    Height = OHeight;
                StrImageThumb = StrFullPath.Substring(0, StrFullPath.LastIndexOf(".")) + "_" + Width.ToString() + "x" + Height.ToString() + "." + Ext;
                StrImageThumb = StrImageThumb.Replace("\\", "/");
                StrImageThumb = StrImageThumb.Replace("//", "/");
                if (FolderThumbnail != "")
                {
                    if (!Directory.Exists(HttpContext.Current.Server.MapPath(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail)))
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail));
                    StrImageThumb = StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail + StrImageThumb.Replace(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")), "");
                }
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrImageThumb)))
                {
                    returnVal = StrImageThumb;
                }
                else
                {
                    if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                    {
                        returnVal = "";
                    }
                    else
                    {
                        string StrPhysicalThumbPath = "";
                        if (((float)OWidth / Width) <= ((float)OHeight / Height))
                        {

                            Ratio = (float)OHeight / (float)Height;
                            RHeight = Height;
                            RWidth = (int)Math.Round((float)OWidth / Ratio);
                        }
                        else
                        {
                            Ratio = (float)OWidth / Width;
                            RWidth = Width;
                            RHeight = (int)Math.Round((float)OHeight / Ratio);
                        }
                        BResize = true;
                        BCrop = false;
                        if (BResize)
                        {
                            StrPhysicalThumbPath = ImageUtils.ResizeImage(HttpContext.Current.Server.MapPath(StrFullPath), HttpContext.Current.Server.MapPath(StrImageThumb), new System.Drawing.Size(Width, Height));

                            if (BCrop)
                            {
                                StrPhysicalThumbPath = Crop(StrPhysicalThumbPath, StrPhysicalThumbPath, Width, Height);
                            }
                            if (StrPhysicalThumbPath != "")
                                returnVal = StrImageThumb;

                        }
                    }
                }
            }
            else
            {
                if (ConvertToDefaultFile)
                {
                    returnVal = GetThumb(DefaultFile, w, h, FolderThumbnail, false, "");
                }
            }
            if (returnVal == "")
            {
                if (ConvertToDefaultFile)
                {
                    returnVal = GetThumb(DefaultFile, w, h, FolderThumbnail, false, "");
                }
            }
            returnVal = returnVal.Replace("//", "/");
            return returnVal;
        }


        public void CreateImageThumb(string StrFile, int Width, int Height, string FolderThumbnail)
        {
            string StrImagePath = CFG.ImagePath();
            string StrImageThumb = "";
            int RWidth = 0;
            int RHeight = 0;
            int w = Width;
            int h = Height;
            float Ratio = 0;

            // Duong dan

            string StrFullPath = StrImagePath + "/" + StrFile;
            StrFullPath = StrFullPath.Replace("\\", "/");
            StrFullPath = StrFullPath.Replace("//", "/");

            if (StrFile != "")
            {

                if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrFullPath)))
                {
                    return;
                }

                string Ext = StrFullPath.Substring(StrFullPath.LastIndexOf(".") + 1);
                System.Drawing.Image OImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(StrFullPath));
                int OWidth = OImage.Width;
                int OHeight = OImage.Height;
                if (Width > OWidth)
                    Width = OWidth;
                if (Height > OHeight)
                    Height = OHeight;
                StrImageThumb = StrFullPath.Substring(0, StrFullPath.LastIndexOf(".")) + "_" + Width.ToString() + "x" + Height.ToString() + "." + Ext;
                StrImageThumb = StrImageThumb.Replace("\\", "/");
                StrImageThumb = StrImageThumb.Replace("//", "/");
                if (FolderThumbnail != "")
                {
                    if (!Directory.Exists(HttpContext.Current.Server.MapPath(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail)))
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail));
                    StrImageThumb = StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")) + "/" + FolderThumbnail + StrImageThumb.Replace(StrImageThumb.Substring(0, StrImageThumb.LastIndexOf("/")), "");
                }
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(StrImageThumb)))
                {
                    System.IO.File.Delete(HttpContext.Current.Server.MapPath(StrImageThumb));
                }

                if (((float)OWidth / Width) <= ((float)OHeight / Height))
                {

                    Ratio = (float)OHeight / (float)Height;
                    RHeight = Height;
                    RWidth = (int)Math.Round((float)OWidth / Ratio);
                }
                else
                {
                    Ratio = (float)OWidth / Width;
                    RWidth = Width;
                    RHeight = (int)Math.Round((float)OHeight / Ratio);
                }
                Resize(HttpContext.Current.Server.MapPath(StrFullPath), HttpContext.Current.Server.MapPath(StrImageThumb), RWidth, RHeight);
            }
        }

        #region Crop
        public string Crop(string PhysicalImagePath, string PhysicalOutPath, int Width, int Height)
        {
            System.Drawing.Image OImage = System.Drawing.Image.FromFile(PhysicalImagePath);
            Bitmap aBitmap = new Bitmap(OImage);
            Rectangle aRecCrop = new Rectangle(0, 0, Width, Height);
            int PX = 0;
            int PY = 0;

            if (Width >= OImage.Width)
                Width = OImage.Width;
            if (Height >= OImage.Height)
            {
                Height = OImage.Height;
            }

            PX = (int)(((float)OImage.Width / 2) - ((float)Width / 2));
            PY = (int)(((float)OImage.Height / 2) - ((float)Height / 2));

            aRecCrop = new Rectangle(PX, PY, Width, Height);

            Bitmap BitmapCrop = new Bitmap(aRecCrop.Width, aRecCrop.Height, aBitmap.PixelFormat);
            Graphics aGraphic = Graphics.FromImage(BitmapCrop);
            Rectangle aRecDest = new Rectangle(0, 0, Width, Height);
            string returnVal = string.Empty;
            try
            {
                aGraphic.CompositingQuality = CompositingQuality.HighQuality;
                aGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                aGraphic.DrawImage(aBitmap, aRecDest, aRecCrop.X, aRecCrop.Y, aRecCrop.Width, aRecCrop.Height, GraphicsUnit.Pixel);
            }
            catch { }
            finally
            {
                OImage.Dispose();
                BitmapCrop.Save(PhysicalOutPath);
            }
            aBitmap.Dispose();
            BitmapCrop.Dispose();
            OImage.Dispose();

            return PhysicalOutPath;
        }
        #endregion

        #region Check Roles
        public bool CheckRoles(string ItemRoles)
        {
            string[] arrRoles = ItemRoles.Split(',');
            foreach (string Item in arrRoles)
            {
                if (Item != "" && Roles.IsUserInRole(Item))
                    return true;
            }

            return false;
        }
        #endregion


        public string Highlight(string StrContent, string StrKeyword)
        {
            string returnValue = StrContent;
            if (returnValue != "" && StrKeyword != "")
            {
                MatchCollection mc = new Regex(StrKeyword, RegexOptions.IgnoreCase).Matches(StrContent);
                for (int i = 0; i < mc.Count && mc[i].Success; i++)
                {
                    ///Return value, break
                    returnValue = returnValue.Replace(mc[i].Value, "<@@@@@@@>" + mc[i].Value + "</@@@@@@@>");
                }
                returnValue = returnValue.Replace("<@@@@@@@>", "<font class=\"highlight\">");
                returnValue = returnValue.Replace("</@@@@@@@>", "</font>");
            }

            return returnValue;
        }
        const string vn1 = "áàảãạâấầẩẫậăắằẳẵặúùủũụưứừửữựóòỏõọôốồổỗộơớờởỡợéèẻẽẹêếềểễệýỳỷỹỵíìỉĩịđ";
        const string vn2 = "aaaaaaaaaaaaaaaaauuuuuuuuuuuoooooooooooooooooeeeeeeeeeeeyyyyyiiiiid";
        public string RemoveAccents(string s)
        {
            string v1 = vn1 + vn1.ToUpper();
            string v2 = vn2 + vn2.ToUpper();
            char ch;
            int index;
            StringBuilder B = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                ch = s[i];
                index = v1.IndexOf(ch);
                if (index != -1)
                    B.Append(v2[index]);
                else
                    B.Append(ch);
            }

            string Val = B.ToString().Trim().Replace("?", "").Replace("`", "").Replace("~", "").Replace("^", "").Replace("'", "").Replace("&", "");
            return Val;
        }
        public string DateToString()
        {
            string result = "";
            ///Value by date
            result += DateTime.Now.Year.ToString();
            result += DateTime.Now.Month.ToString();
            result += DateTime.Now.Day.ToString();
            result += DateTime.Now.Hour.ToString();
            result += DateTime.Now.Minute.ToString();
            result += DateTime.Now.Second.ToString();

            ///Rerurn
            return result;
        }
        public string DateToString(DateTime date)
        {
            string result = "";
            ///Value by date
            result += date.Year.ToString();
            result += date.Month.ToString();
            result += date.Day.ToString();
            result += date.Hour.ToString();
            result += date.Minute.ToString();
            result += date.Second.ToString();

            ///Rerurn
            return result;
        }
        public string GetDateFormat(DateTime date)
        {
            string returnVal = " {0}/{1}/{2}, {3}:{4}";
            returnVal = string.Format(returnVal, date.Day, date.Month, date.Year, date.Hour < 10 ? "0" + date.Hour.ToString() : date.Hour.ToString(), date.Minute < 10 ? "0" + date.Minute.ToString() : date.Minute.ToString());
            switch (date.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    returnVal = "Thứ 2, " + returnVal;
                    break;
                case DayOfWeek.Tuesday:
                    returnVal = "Thứ 3, " + returnVal;
                    break;
                case DayOfWeek.Wednesday:
                    returnVal = "Thứ 4, " + returnVal;
                    break;
                case DayOfWeek.Thursday:
                    returnVal = "Thứ 5, " + returnVal;
                    break;
                case DayOfWeek.Friday:
                    returnVal = "Thứ 6, " + returnVal;
                    break;
                case DayOfWeek.Saturday:
                    returnVal = "Thứ 7, " + returnVal;
                    break;
                case DayOfWeek.Sunday:
                    returnVal = "Chủ nhật, " + returnVal;
                    break;
            }

            return returnVal;
        }

        #region ***ShowMsg - javascript**
        /// <summary>
        /// ShowMsg
        /// </summary>
        /// <param name="Msg">Set Msg</param>
        /// <param name="RedirectURL">Set redirectULR</param>
        /// <param name="PopupURL">Set PopupURL</param>
        /// <param name="Width">Set PopupWidth</param>
        /// <param name="Height">Set PopupHeight</param>
        /// <param name="p">set Page</param>
        public string ShowMsg(string Msg, string RedirectURL, string PopupURL, string Width, string Height, Page p)
        {
            string w = (Width.Length > 1) ? Width : "100";
            string h = (Height.Length > 1) ? Height : "100";
            StringBuilder sbScript = new StringBuilder(string.Empty);
            if (Msg.Length > 1)
                sbScript.AppendLine("alert('" + Msg.Replace(Environment.NewLine, string.Empty) + "');");
            if (PopupURL.Length > 1)
                sbScript.AppendLine("window.open(\"" + PopupURL.Replace(Environment.NewLine, string.Empty) + "\",\"Popup\",\"width=" + w + ",height=" + h + ",menubar=no,scrollbars=yes\");");
            if (RedirectURL.Length > 1)
                sbScript.AppendLine("window.location=\"" + RedirectURL.Replace(Environment.NewLine, string.Empty) + "\";");
            if (!p.ClientScript.IsStartupScriptRegistered("ScriptMsg"))
                ScriptManager.RegisterStartupScript(p, p.GetType(), DateTime.Now.Ticks.ToString(), sbScript.ToString(), true);
            return sbScript.ToString().Replace(Environment.NewLine, string.Empty);
        }
        #endregion

        #region ***Set Culture ***
        /// <summary>
        /// 
        /// </summary>
        CultureInfo aCultureInfo = new CultureInfo("vi-VN", true);
        /// <summary>
        /// 
        /// </summary>
        public CultureInfo myCultureInfo
        {
            get
            {
                aCultureInfo.ClearCachedData();
                aCultureInfo.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
                aCultureInfo.DateTimeFormat.ShortTimePattern = "hh:mm:ss tt";
                aCultureInfo.DateTimeFormat.LongDatePattern = "{0} dd ";
                aCultureInfo.NumberFormat.NumberDecimalDigits = 0;
                aCultureInfo.NumberFormat.CurrencyDecimalDigits = 0;
                return aCultureInfo;
            }
        }
        #endregion

        #region Number to string
        /// <summary>
        /// Hàm đọc từ số thành chữ (Tiếng Việt)
        /// </summary>
        /// <param name="num">Số đưa vào theo dạng chuổi</param>
        /// <returns>Kết quả sau khi đọc</returns>
        public string ReadNumToString(string num)
        {
            //num = Convert.ToDouble(num).ToString();
            double a = 0;
            if (Double.TryParse(num, out a))
            {
                string text = "";
                if (num.Length == 1)
                    text = Doc1So(num);
                else if (num.Length == 2)
                    text = Doc2So(num);
                else if (num.Length == 3)
                    text = Doc3So(num);
                else if (num.Length > 3)
                {
                    int temp = 0;
                    int j = num.Length;

                    while (j > 0)
                    {
                        if (temp + 1 == num.Length)
                            text = text.Insert(0, Doc1So(num.Substring(j - 1, 1)));
                        else if (temp + 2 == num.Length)
                            text = text.Insert(0, Doc2So(num.Substring(j - 2, 2)));
                        else
                        {
                            text = text.Insert(0, Doc3So(num.Substring(j - 3, 3)));
                        }
                        j = j - 3;
                        temp = temp + 3;
                        if (temp < num.Length)
                            text = text.Insert(0, GhepSo(temp));
                    }
                }
                text = text.Trim().Replace("tỷ  triệu  nghìn", " tỷ ").Replace("triệu  nghìn", " triệu ").Replace("tỷ  tỷ", " tỷ ");
                return text = text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1) + " đồng";
            }
            return "";
        }
        private string GhepSo(int index)
        {
            string temp = "";
            if (index == 3)
                temp = " nghìn ";
            else if (index == 6)
                temp = " triệu ";
            else if (index == 9)
                temp = " tỷ ";
            else if (index == 12)
                temp = " nghìn tỷ";
            else if (index == 15)
                temp = " triệu tỷ";
            else if (index == 18)
                temp = " tỷ tỷ ";
            return temp;
        }
        private string Doc3So(string text)
        {
            if (text.Substring(1, 1).Equals("0"))
                if (text.Substring(2, 1).Equals("0"))
                    if (text.Substring(0, 1).Equals("0"))
                        return "";
                    else
                        return Doc1So(text.Substring(0, 1)) + " trăm";
                else
                    return Doc1So(text.Substring(0, 1)) + " trăm lẻ " + Doc1So(text.Substring(2, 1));
            else
                return Doc1So(text.Substring(0, 1)) + " trăm " + Doc2So(text.Substring(1, 2));
        }
        private string Doc2So(string text)
        {
            // neu so dau la so 1
            if (text.Substring(0, 1) == "1")
            {
                //neu so cuoi la so 0
                if (text.Substring(1, 1).Equals("0"))
                    return "mười";
                else if (text.Substring(1, 1).Equals("1"))
                    return "mười một";
                else if (text.Substring(1, 1).Equals("5"))
                    return "mười lăm";
                else
                    return "mười " + Doc1So(text.Substring(1, 1));
            }
            else
            {
                if (text.Substring(1, 1).Equals("0"))
                    return Doc1So(text.Substring(0, 1)) + " mươi";
                else if (text.Substring(1, 1).Equals("5"))
                    return Doc1So(text.Substring(0, 1)) + " mươi lăm";
                else
                    if (text.Substring(1, 1).Equals("1"))
                        return Doc1So(text.Substring(0, 1)) + " mươi mốt";
                    else
                        return Doc1So(text.Substring(0, 1)) + " mươi " + Doc1So(text.Substring(1, 1));
            }
        }
        private string Doc1So(string lsNumber)
        {
            string result = "";
            switch (lsNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        #endregion

        #region FormatDate
        public string ParseDateTimeToEng(string strDate)
        {
            string rs;
            string days, months, years;

            string strD = strDate.Replace("/", " ");
            char[] chr = { ' ' };
            string[] strArray;
            strArray = strD.Split(chr);
            int len = strArray.Length;

            if (len == 3)
            {
                days = strArray[0];
                days = (days.Length < 2) ? "0" + days : days;
                months = strArray[1];
                months = (months.Length < 2) ? "0" + months : months;
                years = strArray[2];
            }
            else if (len == 2)
            {
                days = "01";
                months = strArray[0];
                months = (months.Length < 2) ? "0" + months : months;
                years = strArray[1];
            }
            else//len=1
            {
                days = "01";
                months = "01";
                years = strArray[0];
            }
            rs = months + "/" + days + "/" + years;

            return rs;
        }
        public string ConvertToSqlDateTime(string strDate)
        {
            try
            {
                if (strDate.Length < 0)
                {
                    return "01-01-01";
                }
                else
                {
                    SqlDateTime sdt = SqlDateTime.Parse(ParseDateTimeToEng(strDate));
                    string sdtStr = sdt.ToString();
                    return ParseDateTimeToEng(sdtStr.Substring(0, 10));
                }
            }
            catch (Exception)
            {

                return string.Empty;
            }

        }
        #endregion

        #region ***URL***
        public string EncodeURL(string s)
        {
            return HttpContext.Current.Server.UrlEncode(s.Length > 0 ? s : string.Empty);
        }
        public string DecodeURL(string s)
        {
            return HttpContext.Current.Server.UrlDecode(s.Length > 0 ? s : string.Empty);
        }
        #endregion

        public string getValue(string Table, string Field, string FieldID, object o)
        {
            return Convert.ToString(BaseDataProvider.GetDefaultProviderInstance().ExecuteScalar(
                "SELECT " + Field + " FROM " + Table + " WHERE " + FieldID + " ='" + (o is DBNull ? string.Empty : Convert.ToString(o)) + "'"));
        }
        public string getValue(string Table, string getField, string where)
        {
            ///string sql="SELECT @getField FROM @Table @Where ";
            return Convert.ToString(BaseDataProvider.GetDefaultProviderInstance().ExecuteScalar(
                "SELECT " + getField + " FROM " + Table + " " + where));
        }

        #region ***Resize Image***
        /// <summary>
        /// Resize image
        /// </summary>
        /// <param name="oldSize">
        /// Set oldSize
        /// </param>
        /// <param name="DefaultSize">
        /// Set Default size
        /// </param>
        /// <returns>Size</returns>
        public Size SizeImage(Size oldSize, int DefaultSize)
        {
            Size newSize = new Size();
            if (oldSize.Height > oldSize.Width)
            {
                newSize.Width = (int)(oldSize.Width * ((float)DefaultSize / (float)oldSize.Height));
                newSize.Height = DefaultSize;
            }
            else
            {
                newSize.Width = DefaultSize;
                newSize.Height = (int)(oldSize.Height * ((float)DefaultSize / (float)oldSize.Width));
            }
            return newSize;
        }
        #endregion

        #region ***Decode - Encode**
        /// <summary>
        /// Encode
        /// </summary>
        /// <param name="clearText">
        /// Set string encode
        /// </param>
        /// <param name="password">
        /// Set pass Ex (srgerg$%^bg)
        /// </param>
        /// <param name="salt">
        /// Set salt Ex (Convert.FromBase64String("srfjuoxp"))
        /// </param>
        /// <returns>return string Encode</returns>
        public string Encode(string clearText, string password, byte[] salt)
        {

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.GetBytes(16);
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearBytes, 0, clearBytes.Length);
            cs.Close();
            byte[] EncryptedData = ms.ToArray();
            return Convert.ToBase64String(EncryptedData);
        }

        /// <summary>
        /// Decode
        /// </summary>
        /// <param name="cipherText">
        /// Set string decode
        /// </param>
        /// <param name="password">
        /// Set pass Ex (srgerg$%^bg)
        /// </param>
        /// <param name="salt">
        /// Set salt Ex (Convert.FromBase64String("srfjuoxp"))
        /// </param>
        /// <returns>return string Decode</returns>
        public string Decode(string cipherText, string password, byte[] salt)
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.GetBytes(16);
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherBytes, 0, cipherBytes.Length);
            cs.Close();
            byte[] DecryptedData = ms.ToArray();
            return Encoding.Unicode.GetString(DecryptedData);
        }
        #endregion


        public void Alert(string message, Page obj)
        {
            obj.RegisterClientScriptBlock("Alert", "<script language=javascript>alert(\"" + message + "\");</script>");
        }

        public void Alert(string message, string url, Page obj)
        {
            obj.RegisterClientScriptBlock("Alert", "<script language=javascript>alert(\"" + message + "\"); window.location='" + url + "';</script>");
        }

        public void AlertAndClose(string message, Page obj)
        {
            obj.RegisterClientScriptBlock("Alert", "<script language=javascript>alert(\"" + message + "\"); window.close();</script>");
        }

        public void AlertAndCloseAndReload(string message, Page obj)
        {
            obj.RegisterClientScriptBlock("Alert", "<script language=javascript>alert(\"" + message + "\"); window.close(); window.opener.location=window.opener.location;</script>");
        }

        public string FormatPost(string Text)
        {
            ///string  cOpenTable, cCloseTable;

            //---------- Tiền xử lý các thẻ đơn giản ------
            Text = Text.Replace("<b>", "[[[b]]]");
            Text = Text.Replace("<B>", "[[[b]]]");
            Text = Text.Replace("</b>", "[[[/b]]]");
            Text = Text.Replace("</B>", "[[[/b]]]");

            Text = Text.Replace("<i>", "[[[i]]]");
            Text = Text.Replace("<I>", "[[[i]]]");
            Text = Text.Replace("</i>", "[[[/i]]]");
            Text = Text.Replace("</I>", "[[[/i]]]");

            Text = Text.Replace("<u>", "[[[u]]]");
            Text = Text.Replace("<U>", "[[[u]]]");
            Text = Text.Replace("</u>", "[[[/u]]]");
            Text = Text.Replace("</U>", "[[[/u]]]");

            Text = Text.Replace("<BR>", "[[[br]]]");
            Text = Text.Replace("<br>", "[[[br]]]");

            Text = Text.Replace("</td>", "[[[/td]]]");
            Text = Text.Replace("</TD>", "[[[/td]]]");

            Text = Text.Replace("</tr>", "[[[/tr]]]");
            Text = Text.Replace("</TR>", "[[[/tr]]]");

            Text = Text.Replace("</a>", "[[[/a]]]");
            Text = Text.Replace("</A>", "[[[/a]]]");

            Text = Text.Replace("</font>", "[[[/font]]]");
            Text = Text.Replace("</FONT>", "[[[/font]]]");

            //----------- Chuyển thẻ font -----------------
            string R = Convert.ToString(Regex.Match(Text, "<font[^>]*>"));

            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            ////----------- Chuyển thẻ table -----------------
            //r.Pattern="<table[^>]*>"
            //Set mc = r.Execute(Text)
            //cOpenTable=mc.Count
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            ////----------- Chuyển thẻ /table -----------------
            //r.Pattern="</table>"
            //Set mc = r.Execute(Text)
            //cCloseTable=mc.Count

            //Text=Replace(Text,"</table>","[[[/table]]]")
            //Text=Replace(Text,"</TABLE>","[[[/table]]]")

            //'----------- Chuyển thẻ tr -----------------
            //r.Pattern="<tr[^>]*>"
            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            //'----------- Chuyển thẻ td -----------------
            //r.Pattern="<td[^>]*>"
            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            //'----------- Chuyển thẻ a -----------------
            //r.Pattern="<a[^>]*>"
            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            //'----------- Chuyển thẻ image -----------------
            //r.Pattern="<img[^>]*>"
            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next

            //'----------- Chuyển thẻ style -----------------
            //r.Pattern="<style>[^>]*</style>"
            //Set mc = r.Execute(Text)
            //For Each item in mc
            //    sVal=item.Value
            //    sVal=Replace(sVal,"<","[[[")
            //    sVal=Replace(sVal,">","]]]")
            //    Text = Replace(Text,item,sVal)
            //Next	

            //Set mc = nothing
            //'----------------- Xóa các tag HTML còn lại ----
            //R.Pattern = "<[^>]*>"
            //Text = R.Replace(Text, " ")

            //'----------------- Trả về nguyên trạng ---------
            //Text=Replace(text,"[[[","<")
            //Text=Replace(text,"]]]",">")
            //Text=Replace(text,"&nbsp;"," ")

            //For i=1 to cCloseTable - cOpenTable
            //    Text=Text &"</table>"
            //Next

            return Text;
        }
        public string StripHTML(string source)
        {

            try
            {

                string result;

                // Remove HTML Development formatting
                // Replace line breaks with space
                // because browsers inserts space
                result = source.Replace("\r", " ");
                // Replace line breaks with space
                // because browsers inserts space
                result = result.Replace("\n", " ");
                // Remove step-formatting
                result = result.Replace("\t", string.Empty);
                // Remove repeating speces becuase browsers ignore them
                result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                      @"( )+", " ");

                // Remove the header (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*head([^>])*>", "<head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*head( )*>)", "</head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<head>).*(</head>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all scripts (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*script([^>])*>", "<script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*script( )*>)", "</script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //result = System.Text.RegularExpressions.Regex.Replace(result, 
                //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
                //         string.Empty, 
                //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<script>).*(</script>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all styles (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*style([^>])*>", "<style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*style( )*>)", "</style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<style>).*(</style>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*td([^>])*>", "\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*br( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*li( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*div([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*tr([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*p([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,
                // comments etc - anything thats enclosed inside < >
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<[^>]*>", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&nbsp;", " ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&bull;", " * ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lsaquo;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&rsaquo;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&trade;", "(tm)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&frasl;", "/",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @">", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&copy;", "(c)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&reg;", "(r)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove all others. More can be added, see
                // http://hotwired.lycos.com/webmonkey/reference/special_characters/
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&(.{2,6});", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // for testng
                //System.Text.RegularExpressions.Regex.Replace(result, 
                //       this.txtRegex.Text,string.Empty, 
                //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // make line breaking consistent
                result = result.Replace("\n", "\r");

                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4. 
                // Prepare first to remove any whitespaces inbetween
                // the escaped characters and remove redundant tabs inbetween linebreaks
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\t)", "\t\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\r)", "\t\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\t)", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove multible tabs followind a linebreak with just one tab
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Initial replacement target string for linebreaks
                string breaks = "\r\r\r";
                // Initial replacement target string for tabs
                string tabs = "\t\t\t\t\t";
                for (int index = 0; index < result.Length; index++)
                {
                    result = result.Replace(breaks, "\r\r");
                    result = result.Replace(tabs, "\t\t\t\t");
                    breaks = breaks + "\r";
                    tabs = tabs + "\t";
                }

                // Thats it.
                return result;

            }
            catch
            {
                return source;
            }
        }

        public static void Alert(Control ctrl, string message)
        {
            message = message.Replace("'", "\\'");
            message = message.Replace("\r", "");
            message = message.Replace("\n", "\\n");
            string scriptText = "alert('" + message + "');";
            ScriptManager.RegisterClientScriptBlock(
                ctrl, ctrl.Page.GetType(), Guid.NewGuid().ToString(), scriptText, true);

        }

        public bool IsDomain(string sDomain, string pattern)
        {
            return Regex.IsMatch(sDomain, @"^[a-zA-Z0-9]+([a-zA-Z0-9\-\.]+)(" + pattern.ToString().Replace("_", "|") + ")$", RegexOptions.IgnoreCase);
        }
        //Check Upload file
        public bool CheckFileType(string FileName)
        {
            string ext = Path.GetExtension(FileName);
            if (ext.Equals(".jpg") || ext.Equals(".jpeg") || ext.Equals(".gif") || ext.Equals(".doc") || ext.Equals(".docx") || ext.Equals(".zip") || ext.Equals(".rar"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Get name of Current Page
        /// </summary>
        /// <returns></returns>
        public string GetCurrentPageName()
        {
            string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            return sRet;
        }
        public string readXML_Acitve(string index)
        {
            string result = "", path = HttpContext.Current.Server.MapPath("~/activeMenu.xml");
            createXMLMenu(path);
            Page page = HttpContext.Current.Handler as Page;
            XmlDocument document = new XmlDocument();
            document.Load(path);
            XmlNode node = document.SelectSingleNode("/root/" + page.User.Identity.Name + "");
            if (node == null)
            {
                node = document.CreateNode(XmlNodeType.Element, page.User.Identity.Name, null);
                document.DocumentElement.AppendChild(node);
                document.Save(path);
            }
            else
            {
                XmlNode nodeLevel = document.SelectSingleNode("root/" + page.User.Identity.Name + "/level" + index);
                if (nodeLevel != null)
                {
                    result = nodeLevel.InnerText.Trim();
                }
            }
            return result;
        }
        public void writeXML_Acitve(string index, string newValue)
        {
            string path = HttpContext.Current.Server.MapPath("~/activeMenu.xml");
            createXMLMenu(path);
            Page page = HttpContext.Current.Handler as Page;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);
            XmlElement root = xmlDoc.DocumentElement;
            XmlNode node = xmlDoc.SelectSingleNode("root/" + page.User.Identity.Name + "");
            if (node == null)
            {
                node = xmlDoc.CreateNode(XmlNodeType.Element, page.User.Identity.Name, null);
                xmlDoc.DocumentElement.AppendChild(node);
            }
            if (newValue.IndexOf('_') >= 0)
            {
                string[] arrValue = newValue.Split('_');
                for (int i = 0; i < arrValue.Length; i++)
                {
                    XmlNode nodeLevel = setActive(xmlDoc, node, i.ToString(), arrValue[i], page.User.Identity.Name);
                }
            }
            else
            {
                XmlNode nodeLevel = setActive(xmlDoc, node, index, newValue, page.User.Identity.Name);
            }
            xmlDoc.Save(path);
        }
        private XmlNode setActive(XmlDocument xmlDoc, XmlNode node, string index, string newValue, string username)
        {
            XmlNode nodeLevel = xmlDoc.SelectSingleNode("root/" + username + "/level" + index);
            if (nodeLevel == null)
            {
                nodeLevel = xmlDoc.CreateElement("level" + index);
                nodeLevel.InnerText = newValue;
                node.AppendChild(nodeLevel);
            }
            else
            {
                nodeLevel.InnerText = newValue;
            }
            return nodeLevel;
        }
        private void createXMLMenu(string path)
        {
            if (!File.Exists(path))
            {
                string[] lines = { "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<root>", "</root>" };
                System.IO.File.WriteAllLines(path, lines);
            }
        }

        /// <summary>
        /// Read Content Excel
        /// </summary>
        /// <param name="fileName">Path file Excel</param>
        /// <returns></returns>
        public DataTable ReadExcelContents(string fileName)
        {
            DataTable dt = new DataTable();

            OleDbConnection connection = new OleDbConnection();
            connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + fileName); //Excel 97-2003, .xls //string excelQuery = @"Select [Day],[Outlook],[temp],[Humidity],[Wind], [PlaySport] // FROM [Sheet1$]";
            string excelQuery = @"Select * FROM [Sheet1$]";
            connection.Open();
            OleDbCommand cmd = new OleDbCommand(excelQuery, connection);
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            dt = ds.Tables[0];
            connection.Close();

            return dt;
        }

        public DataTable ReadExcelContents(string fileName, int ts_id, string cc_createdate)
        {
            DataTable dt = new DataTable();

            OleDbConnection connection = new OleDbConnection();
            connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + fileName); //Excel 97-2003, .xls //string excelQuery = @"Select [Day],[Outlook],[temp],[Humidity],[Wind], [PlaySport] // FROM [Sheet1$]";
            string excelQuery = @"Select ID, Email, isERM, " + ts_id + " as [tc_id], '" + cc_createdate + "' as [cc_createdate], CustomerName FROM [Sheet1$]";
            connection.Close();
            connection.Open();
            OleDbCommand cmd = new OleDbCommand(excelQuery, connection);
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            dt = ds.Tables[0];
            connection.Close();

            return dt;
        }

        public string GetDeptName(int Deptid)
        {
            string DeptName = DeptInfo.ConvertDeptIDToName(Deptid);
            return DeptName;
        }

        public long GetCode()
        {
            byte[] gb = Guid.NewGuid().ToByteArray();
            long l = BitConverter.ToInt64(gb, 0);
            return l;
        }
        //Lay IP connect.
        public string GetClientIP()
        {
            string RemoteIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (String.IsNullOrEmpty(RemoteIP))
                RemoteIP = HttpContext.Current.Request.UserHostAddress;

            return RemoteIP;
        }

        public DateTime ParseStringToDateTime(string strDate, int typeFormat)
        {
            DateTime aDateTime;
            DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
            switch (typeFormat)
            {
                case 1://dd/MM/yyyy
                    dtfi.ShortDatePattern = "dd/MM/yyyy";
                    dtfi.DateSeparator = "/";
                    aDateTime = Convert.ToDateTime(strDate, dtfi);
                    break;
                case 2://MM/dd/yyyy
                    dtfi.ShortDatePattern = "MM/dd/yyyy";
                    dtfi.DateSeparator = "/";
                    aDateTime = Convert.ToDateTime(strDate, dtfi);
                    break;
                default:
                    aDateTime = DateTime.Now;
                    break;
            }

            return aDateTime;
        }*/
        #endregion
        const string vn1 = "áàảãạâấầẩẫậăắằẳẵặúùủũụưứừửữựóòỏõọôốồổỗộơớờởỡợéèẻẽẹêếềểễệýỳỷỹỵíìỉĩịđ";
        const string vn2 = "aaaaaaaaaaaaaaaaauuuuuuuuuuuoooooooooooooooooeeeeeeeeeeeyyyyyiiiiid";
        public string RemoveAccents(string s)
        {
            string v1 = vn1 + vn1.ToUpper();
            string v2 = vn2 + vn2.ToUpper();
            char ch;
            int index;
            StringBuilder B = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                ch = s[i];
                index = v1.IndexOf(ch);
                if (index != -1)
                    B.Append(v2[index]);
                else
                    B.Append(ch);
            }

            string Val = B.ToString().Trim().Replace("?", "").Replace("`", "").Replace("~", "").Replace("^", "").Replace("'", "").Replace("&", "").Replace(" ", "-").Replace("--", "-").Replace(".", "");
            return Val;
        }

        #region Paging
        public static string GetPageLinkNormal(int TotalPages, int CurrentPage, string strPage)
        {
            string result = string.Empty;
            const int maxPages = 11;

            if (TotalPages <= maxPages)
            {
                result = buildLinkNormal(1, TotalPages, CurrentPage, null, strPage);
            }
            else
            {
                int pagesAfter = TotalPages - CurrentPage;
                int pagesBefore = CurrentPage - 1;

                if (pagesBefore <= 4)
                {
                    result = buildLinkNormal(1, pagesBefore, CurrentPage, null, strPage);
                }
                else
                {
                    result = buildLinkNormal(1, 1, CurrentPage, null, strPage);
                    int pageSubset = CurrentPage - 5;
                    result += buildLinkNormal(pageSubset, pageSubset, CurrentPage, "...", strPage); // Show page subset (...)
                    result += buildLinkNormal(pageSubset + 1, CurrentPage, CurrentPage, null, strPage);
                }

                if (pagesAfter <= 4)
                {
                    result += buildLinkNormal(CurrentPage + 1, TotalPages, CurrentPage, null, strPage);
                }
                else
                {
                    int pageSubset = CurrentPage + 5;
                    result += buildLinkNormal(pagesBefore > 4 && pagesAfter > 4 ? CurrentPage + 1 : CurrentPage, pageSubset - 1, CurrentPage, null, strPage);
                    result += buildLinkNormal(pageSubset, pageSubset, CurrentPage, "...", strPage); // Show page subset (...)
                    result += buildLinkNormal(TotalPages, TotalPages, CurrentPage, null, strPage);
                }
            }
            return result;
        }

        private static string buildLinkNormal(int start, int end, int CurrentPage, string innerContent, string strPage)
        {
            string result = string.Empty;
            string Url = HttpContext.Current.Request.Url.ToString();
            //Remove Type
            PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
            isreadonly.SetValue(HttpContext.Current.Request.QueryString, false, null);
            HttpContext.Current.Request.QueryString.Remove("Page");
            try
            {
                Url = Url.Substring(0, Url.IndexOf("?", 0));

                if (HttpContext.Current.Request.QueryString.Count > 0)
                {
                    Url += "?" + HttpContext.Current.Request.QueryString + "&";
                }
                else
                {
                    Url += "?";
                }
            }
            catch
            {
                Url = HttpContext.Current.Request.Url.ToString();
            }
            //End Type
            for (int i = start; i <= end; i++)
            {
                result += "<a class='" + (i == CurrentPage ? "current" : "") + "' href='" + Url + "Page=" + i + "'>" + (innerContent ?? i.ToString()) + "</a>";
            }
            return result;

        }

        public static string GetPageLinks(int TotalPages, int CurrentPage, string strPage)
        {
            string result = string.Empty;
            const int maxPages = 11;

            if (TotalPages <= maxPages)
            {
                result = buildLinks(1, TotalPages, CurrentPage, null, strPage);
            }
            else
            {
                int pagesAfter = TotalPages - CurrentPage;
                int pagesBefore = CurrentPage - 1;

                if (pagesBefore <= 4)
                {
                    result = buildLinks(1, pagesBefore, CurrentPage, null, strPage);
                }
                else
                {
                    result = buildLinks(1, 1, CurrentPage, null, strPage);
                    int pageSubset = CurrentPage - 5;
                    result += buildLinks(pageSubset, pageSubset, CurrentPage, "...", strPage); // Show page subset (...)
                    result += buildLinks(pageSubset + 1, CurrentPage, CurrentPage, null, strPage);
                }

                if (pagesAfter <= 4)
                {
                    result += buildLinks(CurrentPage, TotalPages, CurrentPage, null, strPage);
                }
                else
                {
                    int pageSubset = CurrentPage + 5;
                    result += buildLinks(CurrentPage + 1, pageSubset - 1, CurrentPage, null, strPage);
                    result += buildLinks(pageSubset, pageSubset, CurrentPage, "...", strPage); // Show page subset (...)
                    result += buildLinks(TotalPages, TotalPages, CurrentPage, null, strPage);
                }
            }
            return result;
        }

        private static string buildLinks(int start, int end, int CurrentPage, string innerContent, string strPage)
        {
            string result = string.Empty;
            string Url = HttpContext.Current.Request.Url.ToString();
            string strUrl = Name(strPage);
            for (int i = start; i <= end; i++)
            {
                result += "<a class='" + (i == CurrentPage ? "current" : "") + "' href='/" + strUrl.Replace("$" + strPage + "$", i.ToString()) + "'>" + (innerContent ?? i.ToString()) + "</a>";
            }
            return result;

        }

        public static string Name(string strPage)
        {
            UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
            string s = ((System.Web.Routing.Route)HttpContext.Current.Request.RequestContext.RouteData.Route).Url;

            var rd = new RouteValueDictionary(urlHelper.RequestContext.RouteData.Values);
            try
            {
                rd.Remove(strPage);
            }
            catch { }

            foreach (var key in rd.Keys)
            {
                s = s.Replace("{" + key + "}", rd[key].ToString());
            }

            s = Regex.Replace(s, "{" + strPage + "}", "$" + strPage + "$");
            s = Regex.Replace(s, "{\\w+}", "");

            return s;
        }
        #endregion
    }
}